import type { TemplateInfo } from "@/api/topic/topicModel"
import { usePassStore } from "@/store/modules/pass"
import { ref, unref } from "vue"
import { useRouter } from "vue-router"
import { ElMessageBox, ElMessage } from '@toms/element-ui'
import { useI18n } from "vue-i18n"
import { deleteTemplate } from "@/api/pass/template";
import {  TopicStatus } from '@/api/topic/topicModel';
import { deleteTopic, setMerchantTopic } from "@/api/topic/topic"

export function useTopic(request?: Function) {
  const store = usePassStore()
  const { push } = useRouter()  
  const loading = ref(false)
  const { t } = useI18n()
  function setShowBackdrop(templatesInfoVo: TemplateInfo[]) {
    unref(templatesInfoVo).forEach(template => {
      template.showBackdrop = false      
    })
  }

  function editTemplate(template: TemplateInfo, topicId: number) {
    if(topicId) {
      store.setTopicId(topicId)
      store.setTemplateLevel(template.level)
      push({path: `/pass-design/${template.templateId}`, query: { topicId }})
    } 
  }

  async function confirmDeleteTemplate(templateId: number) {
    await ElMessageBox.confirm(
      t('flypass.delete-warning'),
      t('common.prompt'),
      {      
        type: 'warning',
      })
      loading.value = true
      const result = await deleteTemplate(templateId)
      if(result === 1 && request) {
        ElMessage({
          type: 'success',
          message: t('common.message.operation_success')
        })
        await request()
      } else {
        ElMessage({
          type: 'error', 
          message: t('flypass.delete_theme_failed')
        })
      }
      loading.value = false
  }

  async function setTopic(topicId: number) {
    await setMerchantTopic({topicId}) 
    ElMessage({
      type: 'success',
      message: t('common.message.operation_success')
    })  
    request && await request()
  }

  async function deleteTheme(id: number) {    
    await ElMessageBox.confirm(
      t('flypass.delete-warning'),
      t('common.prompt'),
      {      
        type: 'warning',
    })
    const result = await deleteTopic(id)
    if(result) {
      ElMessage({
        type: 'success',
        message: t('common.message.operation_success')
      })  
      request && await request()
    } else {
      ElMessage({
        type: 'error',
        message: t('flypass.delete_theme_failed')
      })
    }
  }

  function goTopicDetail(id: number) {
    push(`/topic/${id}`)
  }

  const mapTagType = {
    [TopicStatus.Normal]: 'info',
    [TopicStatus.InUse]: 'success'
  }
 

  return {
    setShowBackdrop,
    editTemplate,
    confirmDeleteTemplate,
    deleteTheme,
    setTopic,
    goTopicDetail,
    loading,
    mapTagType
  }
}